package com.jsyso.jadmin.sys.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.jsyso.jadmin.common.web.ResponseData;
import com.jsyso.jadmin.common.web.ValidateCodeServlet;
import com.jsyso.jadmin.sys.service.UserService;
import com.jsyso.jsyso.web.WebUtils;

/**
 * 表单验证过滤器
 * @author janjan, xujian_jason@163.com
 *
 */
@Component
public class SysFormAuthenticationFilter extends FormAuthenticationFilter {
	private static Logger logger = LoggerFactory.getLogger(SysFormAuthenticationFilter.class);
	private String messageParam = UserService.DEFAULT_MESSAGE_PARAM;
	
	public String getMessageParam() {
		return messageParam;
	}
	
	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = super.getUsername(request);
		String password = super.getPassword(request);
		String captcha = WebUtils.getParam(request, ValidateCodeServlet.VALIDATE_CODE, "");
		boolean rememberMe = false;
		String host = WebUtils.getRemoteAddr((HttpServletRequest)request);
		if(StringUtils.isBlank(username)) {
			Object usernameParam = request.getAttribute(super.getUsernameParam());
			username = usernameParam == null ? StringUtils.EMPTY : usernameParam.toString();
		}
		if(StringUtils.isBlank(password)) {
			Object passwordParam = request.getAttribute(super.getPasswordParam());
			password = passwordParam == null ? StringUtils.EMPTY : passwordParam.toString();
		}
		return new SysUsernamePasswordToken(username, 
				password.toCharArray(), 
				rememberMe, 
				host, 
				captcha);
	}
	
	/**
	 * 登录成功调用事件
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		WebUtils.renderString(response, ResponseData.success(""));
		return false;
	}
	
	/**
	 * 登录失败调用事件
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		super.onLoginFailure(token, e, request, response);
		String className = e.getClass().getName(), message = "";
		if (IncorrectCredentialsException.class.getName().equals(className)
				|| UnknownAccountException.class.getName().equals(className)){
			message = "用户或密码错误，请重试！";
		} else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
			message = StringUtils.replace(e.getMessage(), "msg:", "");
		} else{
			message = "系统出现点问题，请稍后再试！";
//			e.printStackTrace(); // 输出到控制台
			logger.warn("[系统出错]", e);
		}
//		request.setAttribute(this.getMessageParam(), message);
		WebUtils.renderString(response, ResponseData.error(message));
        return false;
	}
	
}
